package com.hxs.hxsserver.scheduleTask;


import com.hxs.hxsserver.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 数据库备份任务
 *
 */
@Slf4j
@Configuration
@EnableScheduling
public class DatabaseTask {
    /**
     * 数据库端口
     */
    private static final String PORT = "3306";
    /**
     * 数据库服务器所在ip 支持远程的 前提是本地服务器上有mysqldump 命令
     */
    private static final String HOST_IP = "123.207.199.44";
    /**
     * 数据库登录名称
     */
    private static final String USERNAME = "root";
    /**
     * 数据库登录密码
     */
    private static final String PASSWORD = "hxs123hxs";
    /**
     * 备份文件存储在本地的路径 windosw 服务器
     */
    private static final String SAVE_PATH_WINDOWS = "D:\\database\\";
    /**
     * 备份文件存储在本地的路径 linux 服务器
     */
    private static final String SAVE_PATH_LINUX = "/home/back/database/";


    /**
     * 所需要备份的数据库
     */
    private static final String JIMI_HYDRANT = "hxs";


    /**
     * 数据库备份
     */
    @Scheduled(cron = "0 0 2 * * ?")
    public void dbBackUpPaas() {
        try {
            dbBackUp(JIMI_HYDRANT);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 数据库备份
     *
     * @param databaseName 需要备份的数据库的名称
     * @throws Exception 异常
     */
    public static void dbBackUp(String databaseName) throws Exception {
        Date date = new Date();
        String dateStr = DateUtil.dateToString(date, "yyyy-MM-dd");
        String fileName = databaseName + "_" + dateStr + ".sql";
        Calendar calendar = Calendar.getInstance();
        calendar.getTimeInMillis();
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        calendar.add(Calendar.DAY_OF_MONTH,-10);
        String date2 = fmt.format(calendar.getTime());
        String fileName2 = databaseName + "_" + date2 + ".sql";
        File saveFile = new File(savePath());
        // 如果目录不存在
        if (!saveFile.exists()) {
            // 创建文件夹
            saveFile.mkdirs();
        }
        //判断十天前数据库备份文件有没有，如有就删除,只保留十天的数据备份
        File file = new File(savePath()+fileName2);
        if(file.exists()) {
            file.delete();
            log.info("删除数据库备份文件："+fileName2+"时间："+dateStr);
        }
        PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(savePath() + fileName), StandardCharsets.UTF_8));
        Process process = Runtime.getRuntime().exec(getCommand(fileName, databaseName));
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8));
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            printWriter.println(line);
        }
        printWriter.flush();
        if (process.waitFor() != 0) {
            log.info("数据库备份失败！");
        }
    }

    /**
     * get命令
     *
     * @param fileName     文件名称
     * @param databaseName 数据库名称
     * @return {@link String}
     */
    public static String getCommand(String fileName, String databaseName) {
        StringBuilder arg = new StringBuilder();
        arg.append("mysqldump ");
        arg.append(" -h" + HOST_IP);
        arg.append(" -P" + PORT);
        arg.append(" -u" + USERNAME);
        arg.append(" -p" + PASSWORD);
        arg.append(" --skip-opt ");
        arg.append("--add-drop-database ");
        arg.append("--routines ");
        arg.append("--triggers ");
        arg.append("--compress ");
        arg.append("-r");
        arg.append(savePath());
        arg.append(fileName);
        arg.append(" --databases " + databaseName);
        log.info(arg.toString());
        return arg.toString();
    }

    /**
     * 构建存储sql脚本的路径
     *
     * @return
     */
    public static String savePath() {
        String savePath;
        if (isWindows()) {
            savePath = SAVE_PATH_WINDOWS;
        } else {
            savePath = SAVE_PATH_LINUX;
        }
        return savePath;
    }

    /**
     * 判断服务所在系统是什么操作系统
     *
     * @return boolean
     */
    public static boolean isWindows() {
        return System.getProperty("os.name").toLowerCase().contains("windows");
    }
}
